<template>
  <div class="flex mx-5">
    <el-button type="primary" size="default" :disabled="Controldisabled"
      >Ctrl
    </el-button>
    <el-button type="success" size="default" :disabled="Altdisabled"
      >Alt
    </el-button>
    <el-button type="warning" size="default" :disabled="Shiftdisabled"
      >Shift
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

// 创建一个响应式变量来存储按下的键
const pressedKey = ref('')
const Controldisabled = ref(true)
const Altdisabled = ref(true)
const Shiftdisabled = ref(true)

// 定义一个函数来处理键盘按下事件
const handleKeyDown = event => {
  event.preventDefault() // 阻止默认行为
  pressedKey.value = event.key
  updateButtonDisabledState(event.key)
}

// 定义一个函数来处理键盘释放事件
const handleKeyUp = () => {
  pressedKey.value = '' // 重置按下的键
  updateButtonDisabledState(null)
}

// 更新按钮禁用状态的函数
const updateButtonDisabledState = key => {
  if (key) {
    switch (key) {
      case 'Control':
        Controldisabled.value = false
        Altdisabled.value = true
        Shiftdisabled.value = true
        break
      case 'Alt':
        Controldisabled.value = true
        Altdisabled.value = false
        Shiftdisabled.value = true
        break
      case 'Shift':
        Controldisabled.value = true
        Altdisabled.value = true
        Shiftdisabled.value = false
        break
    }
  } else {
    // 如果没有键被按下，重置所有按钮的状态
    Controldisabled.value = true
    Altdisabled.value = true
    Shiftdisabled.value = true
  }
}

// 在组件挂载时添加事件监听器
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
  document.addEventListener('keyup', handleKeyUp) // 添加keyup事件监听
})

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('keyup', handleKeyUp) // 移除keyup事件监听
})
</script>

<style>
/* 你可以在这里添加一些样式 */
</style>
